import React, {useCallback, useEffect, useState} from 'react';
import {Button, message, Pagination, Space, Table, Tooltip} from "antd";
import {EditOutlined, EyeOutlined} from '@ant-design/icons';
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import UserSearch from "../../../components/console/user/userSearch";
import {useNavigate} from "react-router-dom";

const ConsoleUserPage = () => {

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();

    // 分页部分请求参数
    const [paginationReq, setPaginationReq] = useState({
        pageNum: 1,
        pageSize: 10
    });

    // 查询系统用户请求参数
    const [pageSysUserReq, setPageSysUserReq] = useState({
        userAccount: '',
        userNickname: '',
        roleName: ''
    });

    // 分页查询系统用户结果
    const [pageSysUserResp, setSysUserResp] = useState({
        total: 0,
        pageCount: 1,
        records: []
    })

    // 定义分页查询用户的字段
    const pageSysUserRespFields = [
        {
            title: "序号",
            key: "index",
            width: 80,
            align: 'center',
            render: (text, record, index) => {
                return (
                    <div style={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: '#666',
                        fontWeight: 500
                    }}>
                        {(paginationReq.pageNum - 1) * paginationReq.pageSize + index + 1}
                    </div>
                )
            },
            isShow: true
        }, {
            title: "id",
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            isShow: false
        }, {
            title: "账号",
            dataIndex: 'userAccount',
            key: 'userAccount',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#1890ff',
                    fontWeight: 500
                }}>{text}</div>
            )
        }, {
            title: "昵称",
            dataIndex: 'userNickname',
            key: 'userNickname',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#ff3399',
                    fontWeight: 500
                }}>{text}</div>
            )
        }, {
            title: "性别",
            dataIndex: 'userGenderValue',
            key: 'userGenderValue',
            align: 'center',
            isShow: true,
            render: (text) => {
                const bgColor = text === '男' ? '#e6f7ff' : text === '女' ? '#fff0f6' : '#f5f5f5';
                const textColor = text === '男' ? '#1890ff' : text === '女' ? '#f5222d' : '#8c8c8c';

                return (
                    <div style={{
                        display: 'inline-block',
                        padding: '2px 8px',
                        borderRadius: '12px',
                        backgroundColor: bgColor,
                        color: textColor,
                        fontSize: '12px',
                        fontWeight: 500
                    }}>
                        {text}
                    </div>
                );
            }
        }, {
            title: '个人介绍',
            dataIndex: 'userIntroduction',
            key: 'userIntroduction',
            align: 'center',
            isShow: true,
            render: (text) => (
                <Tooltip
                    title={text}
                    placement="rightBottom"
                    mouseEnterDelay={0.3} // 鼠标悬停0.3秒后显示
                    color={'#6600cc'}
                >
                    <div style={{
                        color: '#722ed1',
                        maxWidth: '180px',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        cursor: 'pointer' // 鼠标样式改为手型，暗示可交互
                    }}>
                        {text}
                    </div>
                </Tooltip>
            )
        }, {
            title: '创建时间',
            dataIndex: 'createdTime',
            key: 'createdTime',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#006666',
                    fontSize: '12px'
                }}>{text}</div>
            )
        }, {
            title: '创建人',
            dataIndex: 'createdByUserNickname',
            key: 'createdByUserNickname',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#009999'
                }}>{text}</div>
            )
        }, {
            title: '最后编辑时间',
            dataIndex: 'lastModifiedTime',
            key: 'lastModifiedTime',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#004c99',
                    fontSize: '12px'
                }}>{text}</div>
            )
        }, {
            title: '最后编辑人',
            dataIndex: 'lastModifiedByUserNickname',
            key: 'lastModifiedByUserNickname',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#004c99'
                }}>{text}</div>
            )
        }, {
            title: '操作',
            align: 'center',
            render: (text, record) => (
                <Space size="small">
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EyeOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#1890ff',
                            backgroundColor: 'rgba(24, 144, 255, 0.05)',
                            border: '1px solid #91d5ff',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => redirect2UserDetail('search', record.id)}
                    >
                        查看
                    </Button>
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EditOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#fa8c16',
                            backgroundColor: 'rgba(250, 140, 22, 0.05)',
                            border: '1px solid #ffbb96',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(250, 140, 22, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => redirect2UserDetail('edit', record.id)}
                    >
                        编辑
                    </Button>
                </Space>
            ),
            isShow: true
        }
    ]

    /**
     * 分页查询系统用户
     */
    const pageQuerySysUser = useCallback(() => {
        RequestUtils.post(RequestApis.userManage.page, {
            ...paginationReq,
            ...pageSysUserReq
        })
            .then(res => {
                setSysUserResp(res.data.data);
            })
            .catch(err => {
                messageApi.error(err.message);
            });
    }, [messageApi, pageSysUserReq, paginationReq]);

    /**
     * 跳转用户详情页
     */
    const redirect2UserDetail = (operation, userId) => {
        navigate("/console/user/" + operation + "/" + userId);
    }

    /**
     * 监听分页变化（只在分页参数变化时触发）
     */
    useEffect(() => {
        pageQuerySysUser();
        // 忽略警告, 否则会一直提示需要监听 pageSysUserReq
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [paginationReq]);

    // 表格行样式 - 交替行背景色
    const getRowClassName = (record, index) => {
        return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
    };

    return (
        <div>
            {contextHolder}

            {/* 查询条件 */}
            <div style={{
                padding: '16px'
            }}>
                <UserSearch
                    setPaginationReq={setPaginationReq}
                    pageSysUserReq={pageSysUserReq}
                    setPageSysUserReq={setPageSysUserReq}
                    pageQuerySysUser={pageQuerySysUser}
                />
            </div>

            {/* 表格展示（表头固定，内容滚动） */}
            <div style={{
                backgroundColor: '#fff',
                borderRadius: '8px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.04)',
                overflow: 'hidden',
                transition: 'box-shadow 0.3s ease'
            }} onMouseOver={(e) => {
                e.currentTarget.style.boxShadow = '0 4px 16px rgba(0, 0, 0, 0.08)';
            }} onMouseOut={(e) => {
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.04)';
            }}>
                <Table
                    dataSource={pageSysUserResp.records}
                    columns={pageSysUserRespFields.filter(item => item.isShow)}
                    pagination={false}
                    scroll={{
                        y: 'calc(100vh - 440px)',
                        x: 'max-content'
                    }}
                    bordered={false}
                    rowHoverable
                    style={{width: '100%'}}
                    tableLayout="fixed"
                    rowClassName={getRowClassName}
                    headerStyle={{
                        backgroundColor: '#fafafa',
                        color: '#1f2329',
                        fontWeight: 600,
                        fontSize: '14px',
                        borderBottom: '1px solid #e5e6eb',
                        padding: '12px 16px'
                    }}
                    bodyStyle={{
                        fontSize: '13px'
                    }}
                    rowStyle={{
                        height: '60px',
                        transition: 'background-color 0.2s ease'
                    }}
                    // 添加表格加载状态
                    loading={{
                        spinning: false, // 可以根据实际加载状态设置
                        indicator: <div style={{padding: '40px 0'}}>加载中...</div>
                    }}
                    // 表格行悬停样式
                    onRow={(record, index) => ({
                        onMouseEnter: (e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.02)';
                        },
                        onMouseLeave: (e) => {
                            const isEven = index % 2 === 0;
                            e.currentTarget.style.backgroundColor = isEven ? '#fcfcfc' : '#fff';
                        },
                    })}
                />
            </div>

            {/* 分页组件 */}
            <div style={{
                display: "flex",
                justifyContent: "flex-end",
                alignItems: "center",
                height: '60px',
                marginTop: '16px',
                fontSize: '13px'
            }}>
                <Pagination
                    total={pageSysUserResp.total}
                    current={paginationReq.pageNum}
                    pageSize={paginationReq.pageSize}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => {
                        return (
                            <div style={{fontSize: '15px'}}>
                                <span>共</span>
                                <span style={{color: 'red', fontWeight: 'bold'}}> {total} </span>
                                <span>条数据</span>
                            </div>
                        )
                    }}
                    pageSizeOptions={['10', '20', '50', '100', '200']}
                    onChange={(pageNum, pageSize) => {
                        setPaginationReq({
                            ...paginationReq,
                            pageNum: pageNum,
                            pageSize: pageSize
                        })
                    }}
                    onShowSizeChange={(current, size) => {
                        setPaginationReq({
                            ...paginationReq,
                            pageNum: current,
                            pageSize: size
                        })
                    }}
                    style={{
                        padding: '8px 16px'
                    }}
                    itemStyle={{
                        borderRadius: '4px',
                        margin: '0 2px',
                        transition: 'all 0.2s ease'
                    }}
                    prevIcon={<span style={{transition: 'transform 0.2s ease'}}>←</span>}
                    nextIcon={<span style={{transition: 'transform 0.2s ease'}}>→</span>}
                />
            </div>
        </div>
    );
}

export default ConsoleUserPage;
